import routerIcon from '@/utils/routerIconMapping';
import routerMapping from '@/utils/routerMapping';

function getMenu(state, menuKey) {
  let userRights = state.userRights || [];
  let menuTotal = [], menu = [];
  for (let item of userRights) {
    if (item.code === routerMapping[menuKey].key) {
      menuTotal = item.children || [];
      break;
    }
  }
  for (let item of menuTotal) {
    let icon = routerIcon[item.fullCode] || {};
    let pushItem = {
      url: routerMapping[menuKey][item.fullCode],
      id: item.id,
      name: item.name,
      children: [],
      ...icon
    };
    if (item.children && item.children.length > 0) {
      for (let el of item.children) {
        if (routerMapping[menuKey][el.fullCode] !== false) {
          pushItem.children.push({
            url: routerMapping[menuKey][el.fullCode],
            name: el.name, 
            id: el.id
          })
        }
      }
    }
    if (pushItem.children.length === 0) delete pushItem.children;
    menu.push(pushItem);
  }
  return menu
}

export default {
  // 卖家中心菜单获取
  sellerMenu: state => {
    return getMenu(state, 'sellerCenter');
  },
  // 企业中心菜单获取
  '4sTenantCenter': state => {
    return getMenu(state , '4sTenantCenter');
  },
  // 买家中心菜单获取
  '4sSaleCenter': state => {
    console.log('4sSaleCenter', state)
    return getMenu(state , '4sSaleCenter');
  },
  // 卖家中心控制台特殊处理菜单
  sellerMenuAccessoriesAndFinance: state => {
    let userRights = state.userRights || [];
    let sellerMenuTotal = [], result = {
      accessories: false,
      finance: false
    };
    for (let item of userRights) {
      if (item.code === routerMapping.sellerCenter.key) {
        sellerMenuTotal = item.children || [];
        for (let el of sellerMenuTotal) {
          if (el.children) {
            for (let sub of el.children) {
              if (sub.fullCode === routerMapping.sellerCenter.accessoriesKey) {
                result.accessories = true;
              } else if (sub.fullCode === routerMapping.sellerCenter.financeKey) {
                result.finance = true;
              }
            }
          }
        }
        break;
      }
    }
    return result
  }
}
